package com.config;

import com.common.DataQualityCheckException;
import com.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * @author hexiaoshu
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {


    /**
     * 服务运行日常处理
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = DataQualityCheckException.class)
    @ResponseBody
    public R handle(DataQualityCheckException e, HttpServletRequest request){
        log.error("数据比对异常，"+"报错请求路径:"+request.getRequestURI());
        e.printStackTrace();
        return R.failed("false",e.getMessage());
    }

    /**
     * 服务运行日常处理
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R handle(Exception e, HttpServletRequest request){
        log.error("服务器报错，"+"报错请求路径:"+request.getRequestURI());
        e.printStackTrace();
        return R.failed(e.getMessage(),"system exception");
    }

    // ------ 参数校检异常处理 ------ //
    /**
     * 处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        //下边ResultCodeEnum.PARAMS_BS_ERROR.getCode()就是你自己自定义的返回code码
        return R.failed(message);
    }

    /**
     * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R bindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return R.failed(message);
    }

    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public R constraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return R.failed(message);
    }

    // ------ end ------ //

}
